package com.jn.glide.presenter;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.jn.glide.common.WeakRrfHandler;
import com.jn.glide.contract.MusicContract;
import com.jn.glide.entity.MusicEntity;
import com.jn.glide.http.GlobalRetrofitClient;
import com.jn.glide.service.MusicService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MusicPresenter implements MusicContract.IMusicPresenter {
    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_SUCCESS2 = 10;
    public static final int HTTP_FAIL = 1;
    private MusicContract.IMusicView mMusicView;

    public MusicPresenter(MusicContract.IMusicView view) {
        mMusicView = view;
    }

    @Override
    public void getData() {
        mMusicView.onHttpLoading(true);
        MusicService service = GlobalRetrofitClient.getInstance().create(MusicService.class);
        service.getMusic("json").enqueue(new Callback<MusicEntity>() {
            @Override
            public void onResponse(Call<MusicEntity> call, Response<MusicEntity> response) {
                Message message = Message.obtain();
                message.obj = response.body();
                message.what = HTTP_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<MusicEntity> call, Throwable t) {

            }
        });
    }

    WeakRrfHandler<MusicPresenter> mHandler = new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int result = msg.what;
            switch (result) {
                case HTTP_SUCCESS:
                    MusicEntity music = (MusicEntity) msg.obj;
                    if (mMusicView != null) {
                        mMusicView.onHttpLoading(false);
                        mMusicView.showData(music);
                    }
                    break;
                case HTTP_FAIL:
                    break;
            }
            return false;
        }
    });
}
